<template>
  <div class="user-center-container">
      <!-- 顶部欢迎区域 -->
      <div class="welcome-section">
          <div class="welcome-card">
            <el-upload
    class="avatar-uploader"
    :show-file-list="false"
    :auto-upload="false"
    :on-change="handleChangeFile"
  >
    <!-- 将头像组件作为上传的触发元素 -->
    <el-avatar :size="80" :src="userInfo.uimage" class="cursor-pointer" />
  </el-upload>
              <div class="welcome-text">
                  <h1>欢迎回来，{{ userInfo.uname || '用户' }}</h1>
                  <p>上次登录时间：{{ userInfo.uregtime || '首次登录' }}</p>
              </div>
              <div class="user-stats">
                  <div class="stat-item">
                      <div class="stat-value">{{ userInfo.uintegral || 0 }}</div>
                      <div class="stat-label">积分</div>
                  </div>
                  <div class="stat-item">
                      <div class="stat-value">{{ memberLevel }}</div>
                      <div class="stat-label">会员等级</div>
                  </div>
              </div>
          </div>
      </div>

      <!-- 主要内容区域 -->
      <div class="content-section">
          <!-- 基本信息卡片（带表单验证） -->
          <el-card class="info-card" shadow="hover">
              <template #header>
                  <div class="card-header">
                      <span>基本信息</span>
                      <el-button 
                          type="primary" 
                          size="small" 
                          @click="handleSaveOrEdit"
                          :loading="saveLoading"
                      >
                          {{ editMode ? '保存修改' : '编辑' }}
                      </el-button>
                  </div>
              </template>
              
              <!-- 基础信息表单（带验证） -->
              <el-form 
                  ref="baseInfoFormRef"
                  :model="userInfo" 
                  label-width="100px" 
                  label-position="left"
                  :rules="baseInfoRules"
              >
                  <el-row :gutter="20">
                      <el-col :span="12">
                          <el-form-item label="用户账号">
                              <el-input v-model="userInfo.uaccount" disabled />
                          </el-form-item>
                      </el-col>
                      <el-col :span="12">
                          <el-form-item label="用户姓名" prop="uname">
                              <el-input v-model="userInfo.uname" :disabled="!editMode" />
                          </el-form-item>
                      </el-col>
                  </el-row>
                  
                  <el-row :gutter="20">
                      <el-col :span="12">
                          <el-form-item label="手机号码" prop="utel">
                              <el-input v-model="userInfo.utel" :disabled="!editMode" placeholder="请输入11位手机号" />
                          </el-form-item>
                      </el-col>
                      <el-col :span="12">
                          <el-form-item label="电子邮箱" prop="uemail">
                              <el-input v-model="userInfo.uemail" :disabled="!editMode" placeholder="请输入正确邮箱" />
                          </el-form-item>
                      </el-col>
                  </el-row>
                  
                  <el-row :gutter="20">
                      <el-col :span="12">
                          <el-form-item label="性别" prop="ugender">
                              <el-radio-group v-model="userInfo.ugender" :disabled="!editMode">
                                  <el-radio label="男">男</el-radio>
                                  <el-radio label="女">女</el-radio>
                              </el-radio-group>
                          </el-form-item>
                      </el-col>
                      <el-col :span="12">
                          <el-form-item label="注册时间">
                              <el-input v-model="userInfo.uregtime" disabled />
                          </el-form-item>
                      </el-col>
                  </el-row>
              </el-form>
          </el-card>

          <!-- 账号安全卡片（密码+密码问题修改） -->
          <el-card class="security-card" shadow="hover">
              <template #header>
                  <div class="card-header">
                      <span>账号安全</span>
                  </div>
              </template>
              
              <!-- 修改密码 -->
              <div class="security-item">
                  <div class="security-info">
                      <div class="security-title">登录密码</div>
                      <div class="security-desc">定期更换密码，保护账号安全</div>
                  </div>
                  <el-button type="primary" size="small" plain @click="openPwdDialog">修改密码</el-button>
              </div>
              
              <!-- 修改密码保护问题 -->
              <div class="security-item">
                  <div class="security-info">
                      <div class="security-title">密码保护问题</div>
                      <div class="security-desc">问题：{{ userInfo.upwdask || '未设置' }}</div>
                  </div>
                  <el-button type="primary" size="small" plain @click="openPwdAskDialog">修改问题</el-button>
              </div>
          </el-card>

          <!-- 其他信息卡片 -->
          <el-card class="other-card" shadow="hover">
              <template #header>
                  <div class="card-header">
                      <span>其他信息</span>
                  </div>
              </template>
              
              <el-descriptions :column="2" border>
                  <el-descriptions-item label="用户ID">{{ '无法查看' }}</el-descriptions-item>
                  <el-descriptions-item label="账号状态">
                      <el-tag type="success" v-if="!userInfo.udelete">正常</el-tag>
                      <el-tag type="danger" v-else>已禁用</el-tag>
                  </el-descriptions-item>
                  <el-descriptions-item label="用户备注">{{ userInfo.uremarks || '无' }}</el-descriptions-item>
                  <el-descriptions-item label="用户信息">{{ userInfo.uinfo || '无' }}</el-descriptions-item>
              </el-descriptions>
          </el-card>
      </div>

      <!-- 1. 修改密码弹窗 -->
      <el-dialog title="修改登录密码" v-model="pwdDialogVisible" width="400px">
          <el-form 
              ref="pwdFormRef"
              :model="pwdForm"
              :rules="pwdRules"
              label-width="120px"
              label-position="left"
          >
              <el-form-item label="原密码" prop="oldPwd">
                  <el-input v-model="pwdForm.oldPwd" type="password" placeholder="请输入原密码" />
              </el-form-item>
              <el-form-item label="新密码" prop="newPwd">
                  <el-input v-model="pwdForm.newPwd" type="password" placeholder="6-20位字母/数字/符号" />
              </el-form-item>
              <el-form-item label="确认新密码" prop="confirmPwd">
                  <el-input v-model="pwdForm.confirmPwd" type="password" placeholder="再次输入新密码" />
              </el-form-item>
          </el-form>
          <template #footer>
              <el-button @click="pwdDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="handleUpdatePwd" :loading="pwdLoading">确认修改</el-button>
          </template>
      </el-dialog>

      <!-- 2. 修改密码保护问题弹窗 -->
      <el-dialog title="修改密码保护问题" v-model="pwdAskDialogVisible" width="400px">
          <el-form 
              ref="pwdAskFormRef"
              :model="pwdAskForm"
              :rules="pwdAskRules"
              label-width="120px"
              label-position="left"
          >
              <el-form-item label="密码问题" prop="upwdask">
                  <el-input v-model="pwdAskForm.upwdask" placeholder="请设置密码保护问题" />
              </el-form-item>
              <el-form-item label="问题答案" prop="upwdans">
                  <el-input v-model="pwdAskForm.upwdans" placeholder="请设置问题答案" />
              </el-form-item>
          </el-form>
          <template #footer>
              <el-button @click="pwdAskDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="handleUpdatePwdAsk" :loading="pwdAskLoading">确认修改</el-button>
          </template>
      </el-dialog>
  </div>
</template>

<script setup>
import { onMounted, ref, computed, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElForm } from 'element-plus';
import { findById } from '@/api/User';
import { Edit } from '@/api/User'; // 导入修改个人信息API（假设与基础信息、密码等共用一个接口，或根据实际拆分）
import { uploadFileReq } from '@/api/File';
// 路由实例
const router = useRouter();

// 基础信息相关
const userInfo = ref({}); // 用户信息（绑定表单）
const editMode = ref(false); // 编辑模式开关
const saveLoading = ref(false); // 保存按钮加载状态
const baseInfoFormRef = ref(); // 基础信息表单引用

// 密码修改相关
const pwdDialogVisible = ref(false); // 密码弹窗开关
const pwdForm = reactive({ oldPwd: '', newPwd: '', confirmPwd: '' }); // 密码表单数据
const pwdRules = reactive({ // 密码验证规则
  oldPwd: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
  newPwd: [
      { required: true, message: '请输入新密码', trigger: 'blur' },
      { min: 6, max: 20, message: '密码长度需在6-20位之间', trigger: 'blur' },
      { pattern: /^[\w!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]*$/, message: '密码包含非法字符', trigger: 'blur' }
  ],
  confirmPwd: [
      { required: true, message: '请确认新密码', trigger: 'blur' },
      { 
          validator: (rule, value, callback) => {
              if (value !== pwdForm.newPwd) {
                  callback(new Error('两次密码输入不一致'));
              } else {
                  callback();
              }
          },
          trigger: 'blur'
      }
  ]
});
const pwdLoading = ref(false); // 密码修改加载状态
const pwdFormRef = ref(); // 密码表单引用

// 密码保护问题相关
const pwdAskDialogVisible = ref(false); // 密码问题弹窗开关
const pwdAskForm = reactive({ upwdask: '', upwdans: '' }); // 密码问题表单数据
const pwdAskRules = reactive({ // 密码问题验证规则
  upwdask: [{ required: true, message: '请输入密码保护问题', trigger: 'blur' }],
  upwdans: [{ required: true, message: '请输入问题答案', trigger: 'blur' }]
});
const pwdAskLoading = ref(false); // 密码问题修改加载状态
const pwdAskFormRef = ref(); // 密码问题表单引用

// 基础信息验证规则（重点：手机号正则）
const baseInfoRules = reactive({
  uname: [{ required: true, message: '请输入用户姓名', trigger: 'blur' }],
  utel: [
      { required: true, message: '请输入手机号码', trigger: 'blur' },
      { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的11位手机号', trigger: 'blur' } // 手机号正则
  ],
  uemail: [
      { required: true, message: '请输入电子邮箱', trigger: 'blur' },
      { pattern: /^[\w.-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9.]+$/, message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  ugender: [{ required: true, message: '请选择性别', trigger: 'change' }]
});

// 计算会员等级
const memberLevel = computed(() => {
  const integral = userInfo.value.uintegral || 0;
  if (integral < 500) return '普通会员';
  if (integral < 1000) return '银卡会员';
  if (integral < 2000) return '金卡会员';
  return '钻石会员';
});

// 头像URL（根据性别动态生成）
const avatarUrl = computed(() => {
  return `https://randomuser.me/api/portraits/${userInfo.value.ugender === '女' ? 'women' : 'men'}/${userInfo.value.uid % 100}.jpg`;
});

// 页面挂载时获取用户信息
onMounted(() => {
  const savedUid = localStorage.getItem('shoeCityUid');
  if (!savedUid) {
      router.push('/login');
      return;
  }
  // 获取用户信息（回显数据）
  findById(savedUid).then(res => {
      if (res && res.uid) { // 假设接口返回包含uid的用户信息
          userInfo.value = res;
          // 初始化密码保护问题表单（回显已有问题）
          pwdAskForm.upwdask = res.upwdask || '';
          pwdAskForm.upwdans = res.upwdans || '';
      } else {
          ElMessage.error('获取用户信息失败');
          router.push('/login');
      }
  }).catch(error => {
      console.error('请求用户信息出错:', error);
      ElMessage.error('网络错误，请重试');
      router.push('/login');
  });
});

// 处理编辑/保存切换
const handleSaveOrEdit = async () => {
  if (!editMode.value) {
      // 进入编辑模式
      editMode.value = true;
      return;
  }
  // 保存修改：先验证表单
  const formValid = await baseInfoFormRef.value.validate();
  if (!formValid) return;

  // 准备提交数据（包含uid，确保后端能定位用户）
  const submitData = {
      uid: userInfo.value.uid, // 必须携带用户ID
      uname: userInfo.value.uname,
      utel: userInfo.value.utel,
      uemail: userInfo.value.uemail,
      ugender: userInfo.value.ugender
      // 基础信息不包含密码相关字段，单独处理
  };

  try {
      saveLoading.value = true;
      // 调用修改API
      const res = await Edit(submitData);
      
          ElMessage.success('基础信息修改成功');
          editMode.value = false; // 退出编辑模式
      
  } catch (error) {
      console.error('修改基础信息出错:', error);
      ElMessage.error('网络错误，修改失败');
  } finally {
      saveLoading.value = false;
  }
};

// 打开密码修改弹窗
const openPwdDialog = () => {
  pwdForm.oldPwd = '';
  pwdForm.newPwd = '';
  pwdForm.confirmPwd = '';
  // 重置表单验证状态
  if (pwdFormRef.value) {
      pwdFormRef.value.clearValidate();
  }
  pwdDialogVisible.value = true;
};

// 处理密码修改提交
const handleUpdatePwd = async () => {
  // 验证密码表单
  const formValid = await pwdFormRef.value.validate();
  if (!formValid) return;

  // 准备密码提交数据（包含uid和密码字段）
  const submitData = {
      uid: userInfo.value.uid,
      upwd: pwdForm.newPwd, // 新密码（后端需加密存储）
      oldPwd: pwdForm.oldPwd // 原密码（后端验证）
  };

  try {
      pwdLoading.value = true;
      const res = await Edit(submitData); // 假设共用Edit接口，或单独用updatePwd接口
      
          ElMessage.success('密码修改成功，请重新登录');
          pwdDialogVisible.value = false;
          // 密码修改成功后退出登录（安全考虑）
          localStorage.removeItem('shoeCityUid');
          router.push('/login');
      
  } catch (error) {
      console.error('修改密码出错:', error);
      ElMessage.error('网络错误，修改失败');
  } finally {
      pwdLoading.value = false;
  }
};

// 打开密码保护问题弹窗
const openPwdAskDialog = () => {
  // 重置表单验证状态
  if (pwdAskFormRef.value) {
      pwdAskFormRef.value.clearValidate();
  }
  pwdAskDialogVisible.value = true;
};

// 处理密码保护问题修改提交
const handleUpdatePwdAsk = async () => {
  // 验证密码问题表单
  const formValid = await pwdAskFormRef.value.validate();
  if (!formValid) return;

  // 准备密码问题提交数据
  const submitData = {
      uid: userInfo.value.uid,
      upwdask: pwdAskForm.upwdask,
      upwdans: pwdAskForm.upwdans
  };

  try {
      pwdAskLoading.value = true;
      const res = await Edit(submitData); // 假设共用Edit接口，或单独用updatePwdAsk接口
      
          ElMessage.success('密码保护问题修改成功');
          // 更新用户信息回显
          userInfo.value.upwdask = pwdAskForm.upwdask;
          pwdAskDialogVisible.value = false;
      
  } catch (error) {
      console.error('修改密码保护问题出错:', error);
      ElMessage.error('修改失败');
  } finally {
      pwdAskLoading.value = false;
  }
};



function handleChangeFile(uploadFile){
    //获得当前选中的图片对象
    let file = uploadFile.raw;
    //将file的图片地址 赋值给缩略图数据模型
    //上传逻辑
    uploadFileFunc(file);
}
function uploadFileFunc(file){
  //创建虚拟表单 用于装载上传文件
  let formData = new FormData();
  formData.append("file",file);
  //发送图片
  uploadFileReq(formData)
  .then(data =>{
      //上传成功 将上传图片的url赋值给数据模型
      userInfo.value.uimage = data;
      console.log(userInfo.value)
      Edit(userInfo.value)
  .then(res=>{
  })
  })

}
</script>

<style scoped>
/* 原有样式保持不变，此处省略（与你提供的样式一致） */
.user-center-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', Arial, sans-serif;
}

/* 欢迎区域样式 */
.welcome-section {
  margin-bottom: 30px;
}

.welcome-card {
  background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
  border-radius: 12px;
  padding: 30px;
  color: white;
  display: flex;
  align-items: center;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
}

.user-avatar {
  margin-right: 30px;
}

.welcome-text h1 {
  font-size: 28px;
  margin: 0 0 10px 0;
  font-weight: 500;
}

.welcome-text p {
  font-size: 16px;
  opacity: 0.9;
  margin: 0;
}

.user-stats {
  margin-left: auto;
  display: flex;
}

.stat-item {
  text-align: center;
  margin-left: 40px;
}

.stat-value {
  font-size: 32px;
  font-weight: bold;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  opacity: 0.8;
}

/* 内容区域样式 */
.content-section {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 20px;
}

.info-card {
  grid-column: span 2;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  font-size: 18px;
}

/* 安全卡片样式 */
.security-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
}

.security-item:last-child {
  border-bottom: none;
}

.security-title {
  font-weight: 500;
  margin-bottom: 5px;
}

.security-desc {
  color: #666;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 992px) {
  .content-section {
      grid-template-columns: 1fr;
  }
  
  .info-card {
      grid-column: span 1;
  }
  
  .welcome-card {
      flex-direction: column;
      text-align: center;
  }
  
  .user-stats {
      margin: 20px 0 0 0;
  }
  
  .stat-item {
      margin: 0 20px;
  }
}

@media (max-width: 768px) {
  .user-center-container {
      padding: 15px;
  }
  
  .welcome-card {
      padding: 20px;
  }
  
  .welcome-text h1 {
      font-size: 24px;
  }
  
  .stat-value {
      font-size: 24px;
  }
}
</style>